/**
  全局方法
**/
import Vue from 'vue'
import Axios from 'axios'; // 引入axios
import Global from './global'; // 引入global.js
/*
  ajax 回调
*/
Vue.prototype.Ajax_callback = function (data, func = {},) {
  // 请求结果处理
  if (!data || Object.keys(data).length == 0) return
  if (data.status == 'success' || +data.status === 1) {
    if (func.hasOwnProperty('success')) {
      let funcc = eval(func.success);
      new funcc(data);
    } else {
      this.default_success(data);
    }
  }
  //回调失败方法是否被重写，若被重写，则执行，反之执行默认的失败方法
  if (data.status == 'fail') {

    if (func.hasOwnProperty('fail')) {
      let funcc = eval(func.fail);
      new funcc(data);
    } else {
      this.default_fail(data);
    }
  }
  //回调请求超时方法是否被重写，若被重写，则执行，反之执行默认的失败方法
  if (data.status == 'timeout') {
    if (func.hasOwnProperty('timeout')) {
      let funcc = eval(func.timeout);
      new funcc(data);
    } else {
      this.default_timeout(data);
    }
  }
}
/*
  定义success的回调和默认回调 Ps：default_success 和 success 初始化需保持一致
*/
Vue.prototype.default_success = function (data) {
  this.$message.success(data.msg);
}
/*
  定义fail的回调和默认回调 default_fail 和 fail 初始化需保持一致
*/
Vue.prototype.default_fail = function (data) {
  this.$message.error(data.msg);
}
/*
    定义timeout的回调和默认回调 timeout 和 timeout 初始化需保持一致
*/
Vue.prototype.default_timeout = function (data) {
  this.$message.error(data.msg);
}

Vue.prototype.export_excel = function (url = '', params = {}, name = '导出数据', flag) {
  if (is_empty(url)) {
    this.$message.warning("导出地址不能为空！")
    return false;
  }

  this.$ajax.post(url, params, { responseType: 'blob' }).then(res => {
    console.info(res)
    if (!res) return;
    let filename = null;
    let blob = res.data;

    if (flag === 'zip') {
      filename = res.headers['content-disposition'] ? res.headers['content-disposition'].split(";")[1].split("filename=")[1] : name + '.zip';
    } else if (flag === 'qr') {
      filename = res.headers['content-disposition'] ? res.headers['content-disposition'].split(";")[1].split("filename=")[1] : name;
      filename = decodeURIComponent(filename);
    } else {
      filename = res.headers['content-disposition'] ? res.headers['content-disposition'].split(";")[1].split("filename=")[1] : name + '.xls';
    }

    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      window.navigator.msSaveBlob(blob, filename);
    } else {
      var blobURL = window.URL.createObjectURL(blob);
      var tempLink = document.createElement('a');
      tempLink.style.display = 'none';
      tempLink.href = blobURL;
      tempLink.setAttribute('download', filename);

      if (typeof tempLink.download === 'undefined') {
        tempLink.setAttribute('target', '_blank');
      }

      document.body.appendChild(tempLink);
      tempLink.click();
      document.body.removeChild(tempLink);
      window.URL.revokeObjectURL(blobURL);
    }
  })
}

/**
 * 导出信息
 */
Vue.prototype.exportExcelGet = function (url = '', params = {}, name = '导出数据', flag) {
  if (is_empty(url)) {
    this.$message.warning("导出地址不能为空！")
    return false;
  }

  this.$ajax.get(url, { params, responseType: 'blob' }).then(res => {
    if (!res) return;
    let filename = null;
    let blob = res.data;

    if (flag === 'zip') {
      filename = res.headers['content-disposition'] ? res.headers['content-disposition'].split(";")[1].split("filename=")[1] : name + '.zip';
    } else if (flag === 'qr') {
      filename = res.headers['content-disposition'] ? res.headers['content-disposition'].split(";")[1].split("filename=")[1] : name;
      filename = decodeURIComponent(filename);
    } else {
      filename = res.headers['content-disposition'] ? res.headers['content-disposition'].split(";")[1].split("filename=")[1] : name + '.xls';
    }

    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      window.navigator.msSaveBlob(blob, filename);
    } else {
      var blobURL = window.URL.createObjectURL(blob);
      var tempLink = document.createElement('a');
      tempLink.style.display = 'none';
      tempLink.href = blobURL;
      tempLink.setAttribute('download', filename);

      if (typeof tempLink.download === 'undefined') {
        tempLink.setAttribute('target', '_blank');
      }

      document.body.appendChild(tempLink);
      tempLink.click();
      document.body.removeChild(tempLink);
      window.URL.revokeObjectURL(blobURL);
    }
  })
}

Vue.prototype.e_confirm = function (param = {}) {

  //是否可通过点击遮罩关闭 MessageBox ,默认是
  if (!param.hasOwnProperty('freecolse')) {
    param.freecolse = true;
  }
  if (!param.hasOwnProperty('txt')) {
    param.txt = '确定要进行此操作吗？';
  }
  if (!param.hasOwnProperty('yes')) {
    param.yes = (data => {
      this.$message.error('非法操作！')
    })

  }
  if (!param.hasOwnProperty('cancel')) {
    param.cancel = (data => {
      this.$message.warning('已取消操作！')
    })

  }
  this.$confirm(param.txt, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    closeOnClickModal: param.freecolse,
    type: 'warning'
  }).then(() => {
    var funcc = eval(param.yes);
    new funcc;
  }).catch(() => {
    var funcc = eval(param.cancel);
    new funcc;
  });
}
/**
 * 获取access_token 方法封装
 */
Vue.prototype.get_access_token = function () {
  Axios.get('/accessToken?client_id=' + Global.client_id + '&secret=' + Global.secret)
    .then(response => {
      let data = response.data
      Global.access_token = data.access_token;
      localStorage.setItem('token', Global.access_token);

    });
}
/**
 * 表单验证规则
 */
Vue.prototype.rules = {
  account: {
    reg: /^[\w]{4,16}$/,
    msg: '账号由4~16位英文、数字、下划线组成'
  },
  pwd: {
    reg: /^[\w]{6,16}$/,
    msg: '密码由6~16位英文、数字、下划线组成'
  },
  strongPwd: {
    reg: /^(?![\da-z]+$)(?![\dA-Z]+$)(?![\d!#$%^&*]+$)(?![a-zA-Z]+$)(?![a-z!#$%^&*]+$)(?![A-Z!#$%^&*]+$)[\da-zA-z!#$%^&*]{8,16}$/,
    msg: '密码限制8~16，由数字、大写字母、小写字母，特殊符号3种或3种以上组合组成'
  },
  spaceKey: {
    reg: /^\S+$/,
    msg: '请勿输入空格'
  },
  trim: {
    reg: /(^\S+)|(\S+$)/,
    msg: '内容前后不可有空格'
  },
  leftTrim: {
    reg: /^\S/,
    msg: '内容前不可有空格'
  },
  rightTrim: {
    reg: /\S$/,
    msg: '内容后不可有空格'
  },
  mobile: {
    reg: /^[1][3,4,5,6,7,8,9][0-9]{9}$|^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/,
    msg: '电话格式不正确'
  },
  ip: {
    reg: /^(?:(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:1[0-9][0-9]\.)|(?:[1-9][0-9]\.)|(?:[0-9]\.)){3}(?:(?:2[0-5][0-5])|(?:25[0-5])|(?:1[0-9][0-9])|(?:[1-9][0-9])|(?:[0-9]))$/,
    msg: '请输入正确的ip地址'
  },
  mask: {
    reg: /^(254|252|248|240|224|192|128|0)\.0\.0\.0|255\.(254|252|248|240|224|192|128|0)\.0\.0|255\.255\.(254|252|248|240|224|192|128|0)\.0|255\.255\.255\.(254|252|248|240|224|192|128|0)$/,
    msg: '请输入正确的子网掩码'
  },
  chinese: {
    reg: /^[\u4e00-\u9fa5\w]+$/,
    msg: '请勿输入特殊字符'
  },
  link: {
    reg: /^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i,
    msg: '链接格式错误'
  }
}
